package com.staples.tc.util;

import static com.staples.tc.util.TCIConstants.KEY_MAIL_ADDR_BCC;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_ADDR_CC;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_ADDR_FROM;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_ADDR_TO;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_BODY_BADINPUT;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_BODY_PREFIX;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_BODY_SUFFIX;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_HOST;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_PORT;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_SUBJECT;
import static com.staples.tc.util.TCIConstants.KEY_MAIL_SUBJECT_BADINPUT;
import static com.staples.tc.util.TCIConstants.MAIL_CONTENT_HTML;
import static com.staples.tc.util.TCIConstants.MAIL_PROP_HOST;
import static com.staples.tc.util.TCIConstants.MAIL_PROP_PORT;
import static com.staples.tc.util.TCIConstants.SPLIT_CHAR;

import java.io.StringWriter;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.staples.tc.exception.CCardJobException;

/**
 * Helper class to CCardTidalJobMain
 * @author Cognizant Technology Solutions.
 *
 */
public class CCardJobUtil {
	private static final Logger logger = Logger.getLogger(CCardJobUtil.class);
	private static Transformer transformer;
	
	/**
	 * converts Document formatted message to String
	 * @param document
	 * @return
	 */
	public String documentToStringConv(Document document) throws CCardJobException {
		logger.debug("Entering documentToStringConv() ....");
		String docstr = null;
		try {
			if (transformer == null) {
				TransformerFactory tf = TransformerFactory.newInstance();
				transformer = tf.newTransformer();
			}
			StringWriter sw = new StringWriter();
			transformer.transform(new DOMSource(document), new StreamResult(sw));
			docstr = sw.toString();
			logger.debug("after transition from doc to StreamResult>>> ");
		} catch (TransformerException tExp) {
			logger.error("TransformerException while converting document to String ..." + tExp.getMessage());
			throw new CCardJobException(tExp.getMessage(), tExp);
		} catch (Exception exp) {
			logger.error("Exception while converting document to String ..." + exp.getMessage());
			throw new CCardJobException(exp.getMessage(), exp);
		} 
		logger.debug("Exiting documentToStringConv() ....");
		return docstr;
	}
	

	/**
	 * 
	 * @param orderNum
	 * @param rewardNum
	 * @param companyName
	 * @throws CCardJobException
	 */
	public void sendAlertMail(String orderNum, String rewardNum, String companyName) throws CCardJobException {
		logger.debug("Entering mailTrigger() ....");
		try {
			final String emailHost = TCIResourceBundle.getProperty(KEY_MAIL_HOST);
			final int emailPort = Integer.parseInt(TCIResourceBundle.getProperty(KEY_MAIL_PORT));
			final String emailAddrFrom = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_FROM);
			final String[] emailAddrTo = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_TO).split(SPLIT_CHAR);
			final String[] emailAddrCC = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_CC).split(SPLIT_CHAR);
			final String[] emailAddrBCC = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_BCC).split(SPLIT_CHAR);
			final String emailSubject = TCIResourceBundle.getProperty(KEY_MAIL_SUBJECT) + orderNum;
			final String emailContent = TCIResourceBundle.getProperty(KEY_MAIL_BODY_PREFIX) + rewardNum + " " + TCIResourceBundle.getProperty(KEY_MAIL_BODY_SUFFIX) + companyName;
			this.sendMail(emailHost, emailPort, emailAddrFrom, emailSubject, emailContent, emailAddrTo, emailAddrCC, emailAddrBCC);
		} catch (CCardJobException cExp){
			logger.error("CCardJobException occured while sending email ...", cExp);
//			throw cExp;
		} catch (Exception exp) {
			logger.error("Exception occured while sending email ...", exp);
//			throw new CCardJobException(exp.getMessage(), exp);
		}
		logger.debug("Exiting mailTrigger() ....");
	}
	
	
	/**
	 * 
	 * @throws CCardJobException
	 */
	public void sendBadInputAlertMail() throws CCardJobException {
		logger.debug("Entering mailTriggerBadInput() ....");
		try {
			final String emailHost = TCIResourceBundle.getProperty(KEY_MAIL_HOST);
			final int emailPort = Integer.parseInt(TCIResourceBundle.getProperty(KEY_MAIL_PORT));
			final String emailAddrFrom = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_FROM);
			final String[] emailAddrTo = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_TO).split(SPLIT_CHAR);
			final String emailAddrCC[] = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_CC).split(SPLIT_CHAR);
			final String emailAddrBCC[] = TCIResourceBundle.getProperty(KEY_MAIL_ADDR_BCC).split(SPLIT_CHAR);
			final String emailSubject = TCIResourceBundle.getProperty(KEY_MAIL_SUBJECT_BADINPUT);
			final String emailContent = TCIResourceBundle.getProperty(KEY_MAIL_BODY_BADINPUT);
			this.sendMail(emailHost, emailPort, emailAddrFrom, emailSubject, emailContent, emailAddrTo, emailAddrCC, emailAddrBCC);
		} catch (CCardJobException cExp){
			logger.error("CCardJobException occured while sending bad input email ...", cExp);
//			throw cExp;
		} catch (Exception exp) {
			logger.error("Exception occured while sending bad input email ...", exp);
//			throw new CCardJobException(exp.getMessage(), exp);
		}
		logger.debug("Exiting mailTriggerBadInput() ....");
	}

	
	/**
	 * 
	 * @param emailHost
	 * @param emailPort
	 * @param emailAddrFrom
	 * @param emailSubject
	 * @param emailContent
	 * @param emailAddrTo
	 * @param emailAddrCC
	 * @param emailAddrBCC
	 * @throws CCardJobException
	 */
	private void sendMail(String emailHost, int emailPort, String emailAddrFrom, 
			String emailSubject, String emailContent, String[] emailAddrTo, 
			String[] emailAddrCC, String[] emailAddrBCC) throws CCardJobException {
		logger.debug("Entering sendMail() ....");
		try {
			Properties prop = new Properties();
			prop.put(MAIL_PROP_HOST, emailHost);
			prop.put(MAIL_PROP_PORT, emailPort);

			StringBuilder contentbuff = new StringBuilder();
			Session session = Session.getDefaultInstance(prop, null);
			session.setDebug(false);

			Message msg = new MimeMessage(session);
			InternetAddress addressFrom = new InternetAddress(emailAddrFrom);
			InternetAddress[] msgAddrTo = new InternetAddress[emailAddrTo.length];
			for (int i = 0; i < msgAddrTo.length; i++) {
				msgAddrTo[i] = new InternetAddress(emailAddrTo[i]);
			}
			msg.setRecipients(Message.RecipientType.TO, msgAddrTo);
			msg.setFrom(addressFrom);
			// If CC field is present then this routine
			if (emailAddrCC != null && emailAddrCC.length > 0) {
				InternetAddress[] addressCC = new InternetAddress[emailAddrCC.length];
				for (int i = 0; i < addressCC.length; i++) {
					addressCC[i] = new InternetAddress(emailAddrCC[i]);
				}
				msg.setRecipients(Message.RecipientType.CC, addressCC);
			}
			// If BCC field is present then this routine
			if (emailAddrBCC != null && emailAddrBCC.length > 0) {
				InternetAddress[] addressBCC = new InternetAddress[emailAddrBCC.length];
				for (int i = 0; i < addressBCC.length; i++) {
					addressBCC[i] = new InternetAddress(emailAddrBCC[i]);
				}
			}

			contentbuff.append(emailContent);
			msg.setSubject(emailSubject);
			msg.setContent(contentbuff.toString(), MAIL_CONTENT_HTML);
			logger.debug("Sending Mail ....");
			Transport.send(msg);
			logger.debug("Mail trigger complete ....");
		} catch (MessagingException mExp) {
			logger.error("MessagingException while sending email ..." + mExp.getMessage());
			throw new CCardJobException(mExp.getMessage(), mExp);
		} 
		logger.debug("Exiting sendMail() ....");
	}
	
	
	
	public static boolean isStrNotEmpty(String strInput) {
		boolean flag = false;
		if (strInput != null && !strInput.trim().equals("")) {
			flag = true;
		} 
		return flag;
	}
	
	public static String stripWhiteSpaces(String inpStr) {
		String outputStr = "";
		if (CCardJobUtil.isStrNotEmpty(inpStr)) {
			outputStr = inpStr.replaceAll("\\s", "");
		}
		return outputStr;
	}

}


